package mammuthus.web.db

import org.squeryl.PrimitiveTypeMode._
import org.squeryl.{Session, SessionFactory, Schema}
import org.squeryl.annotations.Column
import java.util.Date
import org.squeryl.adapters.MySQLAdapter
import scala.io.Source

/**
 * 5/29/15 WilliamZhu(allwefantasy@gmail.com)
 */

class TTestConf(val id: Long, var name: String, var  user: String, var  url: String, var host: String, @Column("insert_time")var insertTime: Date) {
  def this(name: String, user: String, url: String, host: String) = this(0, name, user, url, host, new Date())
}

object TTestConf {
  def find(name: String) = {
    transaction {
      from(DB.tTestConf)(s => where(s.name === name) select (s)).singleOption
    }
  }

  def updateConf(tTestConf: TTestConf) = {
    transaction {
      update(DB.tTestConf)(s =>
        where(s.name === tTestConf.name)
          set(s.host := tTestConf.host, s.url := tTestConf.url, s.user := tTestConf.user))
      //update(tTestConf)(s => where(s.name === tTestConf.name) select (s)).singleOption
    }
  }
}

object DB extends Schema {


  def init = {}
  val jdbcConfig = Source.fromInputStream(DB.getClass.getResourceAsStream("/jdbc.properties")).getLines().map {
    f =>
      val abc = f.split("=")
      if (abc.length == 2) (abc(0), abc(1))
      else (abc(0), abc.takeRight(abc.length - 1).mkString("="))
  }.toMap

  Class.forName("com.mysql.jdbc.Driver");

  SessionFactory.concreteFactory = Some(() =>
    Session.create(
      java.sql.DriverManager.getConnection(jdbcConfig("url"), jdbcConfig("userName"), jdbcConfig("password")),
      new MySQLAdapter)
  )
  val tTestConf = table[TTestConf]("t_test_conf")

}

object Test {
  def main(args: Array[String]): Unit = {
    DB
    TTestConf.find("java") match {
      case Some(i) =>
      case None =>
        transaction{
          DB.tTestConf.insert(new TTestConf("java","webuser","url","mmmm"))
        }

    }
  }
}
